package com.imooc.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.imooc.pojo.Users;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.service.UserService;
import com.imooc.utils.IMoocJSONResult;
import com.imooc.utils.MD5Utils;
import com.utils.AesCbcUtil;
import com.utils.HttpRequest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value="用户注册登录的接口", tags= {"注册和登录的controller"})
public class RegistLoginController extends BasicController {
	
	@Autowired
	private UserService userService;
	
	@ApiOperation(value="用户注册", notes="用户注册的接口")
	@PostMapping("/regist")
	public IMoocJSONResult regist(@RequestBody Users user) throws Exception {
		
		// 1. 判断用户名和密码必须不为空
		if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			return IMoocJSONResult.errorMsg("用户名和密码不能为空");
		}
		
		// 2. 判断用户名是否存在
		boolean usernameIsExist = userService.queryUsernameIsExist(user.getUsername());
		
		// 3. 保存用户，注册信息
		if (!usernameIsExist) {
			user.setNickname(user.getUsername());
			user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
			user.setFansCounts(0);
			user.setReceiveLikeCounts(0);
			user.setFollowCounts(0);
			userService.saveUser(user);
		} else {
			return IMoocJSONResult.errorMsg("用户名已经存在，请换一个再试");
		}
		
		user.setPassword("");
		
//		String uniqueToken = UUID.randomUUID().toString();
//		redis.set(USER_REDIS_SESSION + ":" + user.getId(), uniqueToken, 1000 * 60 * 30);
//		
//		UsersVO userVO = new UsersVO();
//		BeanUtils.copyProperties(user, userVO);
//		userVO.setUserToken(uniqueToken);
		
		UsersVO userVO = setUserRedisSessionToken(user);
		
		return IMoocJSONResult.ok(userVO);
	}
	
	public UsersVO setUserRedisSessionToken(Users userModel) {
		String uniqueToken = UUID.randomUUID().toString();
		redis.set(USER_REDIS_SESSION + ":" + userModel.getId(), uniqueToken, 1000 * 60 * 30);
		
		UsersVO userVO = new UsersVO();
		BeanUtils.copyProperties(userModel, userVO);
		userVO.setUserToken(uniqueToken);
		return userVO;
	}
	
	@ApiOperation(value="用户登录", notes="用户登录的接口")
	@PostMapping("/login")
	public IMoocJSONResult login(@RequestBody Users user) throws Exception {
		String username = user.getUsername();
		String password = user.getPassword();
		
//		Thread.sleep(3000);
		
		// 1. 判断用户名和密码必须不为空
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return IMoocJSONResult.ok("用户名或密码不能为空...");
		}
		
		// 2. 判断用户是否存在
		Users userResult = userService.queryUserForLogin(username, 
				MD5Utils.getMD5Str(user.getPassword()));
		
		// 3. 返回
		if (userResult != null) {
			userResult.setPassword("");
			UsersVO userVO = setUserRedisSessionToken(userResult);
			return IMoocJSONResult.ok(userVO);
		} else {
			return IMoocJSONResult.errorMsg("用户名或密码不正确, 请重试...");
		}
	}
	
	@ApiOperation(value="用户注销", notes="用户注销的接口")
	@ApiImplicitParam(name="userId", value="用户id", required=true, 
						dataType="String", paramType="query")
	@PostMapping("/logout")
	public IMoocJSONResult logout(String userId) throws Exception {
		redis.del(USER_REDIS_SESSION + ":" + userId);
		return IMoocJSONResult.ok();
	}
	
	@ResponseBody  
	@RequestMapping("/onelogin")  
    public IMoocJSONResult decodeUserInfo(String encryptedData, String iv, String code) {  
 
	Users user = new Users();
    Map<String, Object> map = new HashMap<String, Object>();  
 
    // 登录凭证不能为空  
    if (code == null || code.length() == 0) {  
        return IMoocJSONResult.errorException("code 不能为空");  
    }  
 
    // 小程序唯一标识 (在微信小程序管理后台获取)  
    String wxspAppid = "wxae7223fbd2d5c507";  
    // 小程序的 app secret (在微信小程序管理后台获取)  
    String wxspSecret = "47d99d0c659f61f4947394bcb4da2407";  
    // 授权（必填）  
    String grant_type = "authorization_code";  
 
   
    //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid  
    //////////////// ////////////////  
    // 请求参数  
    String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type="  
            + grant_type;  
    // 发送请求  
    String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params); 
    
   
    // 解析相应内容（转换成json对象）  
    JSONObject json = new JSONObject(sr);  
    // 获取会话密钥（session_key）  
    String session_key = json.get("session_key").toString();  
    // 用户的唯一标识（openid）  
    String openid = (String) json.get("openid");  
 
    //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////  
    try {  
        String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");  
        if (null != result && result.length() > 0) {  
            JSONObject userInfoJSON = new JSONObject(result);  
            // 解密unionId & openId;  
            if (!userInfoJSON.isNull("openId")) {
            	//  判断用户名是否存在
             	boolean usernameIsExist = userService.queryUsernameIsExist(userInfoJSON.get("openId").toString());
             	//  不存在：保存用户，注册信息，登陆
        		if (!usernameIsExist) {
        			user.setNickname(userInfoJSON.get("nickName").toString());
        			user.setPassword(MD5Utils.getMD5Str("123456"));
        			user.setFansCounts(0);
        			user.setReceiveLikeCounts(0);
        			user.setFollowCounts(0);
        			user.setUsername(userInfoJSON.get("openId").toString());
        			user.setFaceImage("/videos_dev/pages/resource/images/noneface.png");
        			userService.saveUser(user);
        		} else {
        		//  存在：读取信息
        			user = userService.queryUserForLogin(userInfoJSON.get("openId").toString(), 
        			MD5Utils.getMD5Str("123456"));
        		}
        		UsersVO userVO = setUserRedisSessionToken(user);
    			return IMoocJSONResult.ok(userVO);
			}
        }else {
        		return IMoocJSONResult.errorMsg("解密失败");
        }
    }catch (Exception e) {  
        e.printStackTrace();  
    }
	return IMoocJSONResult.errorMsg("发生错误"); 
	}
}
